<template>
  <div class="connection-container">
    <el-row :gutter="20">
      <el-col :span="18">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>数据库连接管理</span>
              <div class="header-actions">
                <el-button type="primary" @click="handleCreate">
                  <el-icon><Plus /></el-icon>新建连接
                </el-button>
                <el-button type="success" @click="handleRefresh">
                  <el-icon><Refresh /></el-icon>刷新
                </el-button>
              </div>
            </div>
          </template>
          
          <el-table 
            :data="connectionList" 
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="sqlName" label="数据库名称" width="150">
              <template #default="{ row }">
                <el-link 
                  type="primary" 
                  @click="handleTableManage(row)"
                  :disabled="row.status !== 1"
                >
                  {{ row.sqlName }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="ip" label="IP地址" width="150" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="type" label="数据库类型" width="120">
              <template #default="{ row }">
                {{ databaseTypes[row.type] || '未知' }}
              </template>
            </el-table-column>
            <el-table-column prop="port" label="端口" width="100" />
            <el-table-column label="连接状态" width="100">
              <template #default="{ row }">
                <el-tooltip :content="row.status === 1 ? '可连接' : '不可连接'" placement="top">
                  <el-icon 
                    :size="20" 
                    :color="row.status === 1 ? '#67C23A' : '#F56C6C'"
                    class="status-icon"
                  >
                    <Check v-if="row.status === 1" />
                    <Close v-else />
                  </el-icon>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button
                  type="success"
                  size="small"
                  @click="handleTest(scope.row)"
                >
                  <el-icon><Check /></el-icon>
                  测试
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="暂无连接数据" />
            </template>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.current"
              v-model:page-size="pagination.size"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="status-card">
          <template #header>
            <span>连接状态统计</span>
          </template>
          <div class="status-list">
            <div class="status-item">
              <el-tag type="success">可连接</el-tag>
              <span class="status-value">{{ statusCount.success }}</span>
            </div>
            <div class="status-item">
              <el-tag type="danger">不可连接</el-tag>
              <span class="status-value">{{ statusCount.fail }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 创建/编辑连接对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建连接' : '编辑连接'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="数据库名称" prop="sqlName">
          <el-input v-model="form.sqlName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入数据库IP地址" />
        </el-form-item>
        <el-form-item label="数据库类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择数据库类型">
            <el-option
              v-for="(name, type) in databaseTypes"
              :key="type"
              :label="name"
              :value="Number(type)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入数据库用户名" />
        </el-form-item>
        <el-form-item 
          label="密码" 
          prop="password"
        >
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入数据库密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number 
            v-model="form.port" 
            :min="1" 
            :max="65535"
            placeholder="请输入端口号"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表列表对话框 -->
    <el-dialog
      v-model="tableDialogVisible"
      :title="'数据库表列表 - ' + currentConnection?.sqlName"
      width="600px"
    >
      <el-table 
        :data="tableList" 
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="name" label="表名" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tableDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from 'axios'
import {
  Plus,
  Refresh,
  Delete,
  Check,
  Close
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const dialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref(null)
const loading = ref(false)
const router = useRouter()

// 数据库类型映射
const databaseTypes = {
  1: 'MySQL',
  2: 'PostgreSQL'
}

const form = reactive({
  id: null,
  sqlName: '',
  ip: '',
  username: '',
  password: '',
  type: 1,
  port: 3306
})

const rules = {
  sqlName: [
    { required: true, message: '请输入数据库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号范围为1-65535', trigger: 'blur' }
  ]
}

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 连接列表数据
const connectionList = ref([])
const statusCount = reactive({ success: 0, fail: 0 })

const countStatus = () => {
  let success = 0, fail = 0
  connectionList.value.forEach(item => {
    if (item.status === 1) success++
    else fail++
  })
  statusCount.success = success
  statusCount.fail = fail
}

// 获取连接列表
const fetchConnectionList = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/connection/list', {
      params: {
        current: pagination.current,
        size: pagination.size
      }
    })
    if (response.data.code === '200') {
      connectionList.value = response.data.data.data || []
      pagination.total = response.data.data.total || 0
      countStatus()
    } else {
      ElMessage.error(response.data.message || '获取连接列表失败')
    }
  } catch (error) {
    console.error('获取连接列表失败:', error)
    ElMessage.error('获取连接列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取列表
onMounted(() => {
  fetchConnectionList()
})

const handleCreate = () => {
  dialogType.value = 'create'
  dialogVisible.value = true
  // 重置表单数据
  Object.assign(form, {
    id: null,
    sqlName: '',
    ip: '',
    username: '',
    password: '',
    type: 1,
    port: 3306
  })
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 确保所有字段都被正确赋值
  form.id = row.id
  form.sqlName = row.sqlName || ''
  form.ip = row.ip || ''
  form.username = row.username || ''
  form.password = row.password || ''
  form.type = row.type || 1
  form.port = row.port || 3306
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除连接 "${row.username}" 吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.delete(`/api/connection${row.id}/delete`)
      if (response.data.code === '200') {
        ElMessage.success('删除成功')
        fetchConnectionList()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleTest = async (row) => {
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在测试连接...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    const response = await axios.post('/api/connection/test', {
      id: row.id
    })
    
    // 关闭加载状态
    loadingInstance.close()
    
    if (response.data.code === '200') {
      ElMessage({
        message: response.data.data || '连接测试成功',
        type: 'success',
        duration: 3000
      })
      // 刷新列表以更新状态
      fetchConnectionList()
    } else {
      ElMessage({
        message: response.data.data || '连接测试失败',
        type: 'error',
        duration: 3000
      })
    }
  } catch (error) {
    console.error('测试连接失败:', error)
    ElMessage({
      message: error.response?.data?.message || '连接测试失败，请稍后重试',
      type: 'error',
      duration: 3000
    })
  }
}

const handleRefresh = () => {
  fetchConnectionList()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 构建请求参数，确保所有字段都有值
    const requestData = {
      id: form.id,
      sqlName: form.sqlName || '',
      ip: form.ip || '',
      username: form.username || '',
      password: form.password || '',
      type: form.type || 1,
      port: form.port || 3306
    }
    
    console.log('提交的数据:', requestData) // 添加日志
    
    const response = await axios.post('/api/connection/add', requestData)
    
    if (response.data.code === '200') {
      dialogVisible.value = false
      ElMessage.success(dialogType.value === 'create' ? '创建成功' : '修改成功')
      fetchConnectionList()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('操作失败')
  }
}

const tableDialogVisible = ref(false)
const tableLoading = ref(false)
const tableList = ref([])
const currentConnection = ref(null)

const handleTableManage = (row) => {
  if (row.status !== 1) {
    ElMessage.warning('请先测试连接后再管理表')
    return
  }
  // 跳转到表管理页面，并传递数据库ID
  router.push({
    path: '/database/tables',
    query: { connectionId: row.id }
  })
}

const handlePageChange = (page) => {
  handleExecute(page, pagination.value.size)
}
const handleSizeChange = (size) => {
  handleExecute(1, size)
}
</script>

<style scoped>
.connection-container {
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-actions {
  display: flex;
  gap: 12px;
}

:deep(.el-card) {
  width: 100%;
  height: 100%;
}

:deep(.el-table) {
  width: 100% !important;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-input-number) {
  width: 100%;
}

.status-icon {
  cursor: pointer;
  transition: transform 0.3s;
}

.status-icon:hover {
  transform: scale(1.2);
}

.table-wrapper {
  /* 不要有 flex、overflow、height，只保留 padding-bottom: 0; 或直接去掉 */
}
.query-result, .results-wrapper {
  /* 不要有 flex: 1; 或 overflow: hidden; */
}

.status-card {
  margin-top: 0;
}
.status-list {
  padding: 20px 0 0 0;
}
.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.status-value {
  margin-left: 16px;
  font-size: 16px;
  color: var(--text-color, #333);
}
</style> 